using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Util;
using Admin.NET.Core;
using Admin.NET.Core.Service;
using Furion.Schedule;
using Microsoft.Extensions.DependencyInjection;

namespace Admin.NET.Application.Job;

[JobDetail("job_loadbrandmodel", Description = "加载品牌型号", GroupName = "default", Concurrent = false)]
[PeriodMinutes(30L, TriggerId = "trigger_loadbrandmodel", Description = "加载品牌型号", RunOnStart = true)]
public class LoadBrandModelJob : IJob
{
	private readonly IServiceScopeFactory _scopeFactory;

	public LoadBrandModelJob(IServiceScopeFactory scopeFactory)
	{
		_scopeFactory = scopeFactory;
	}

	public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
	{
		using IServiceScope serviceScope = _scopeFactory.CreateScope();
		SqlSugarRepository<BrandModel> _rep = serviceScope.ServiceProvider.GetService<SqlSugarRepository<BrandModel>>();
		SqlSugarRepository<AggrementPluginManage> _pluginRep = serviceScope.ServiceProvider.GetService<SqlSugarRepository<AggrementPluginManage>>();
		SysCacheService _cache = serviceScope.ServiceProvider.GetService<SysCacheService>();
		List<BrandModel> all = await _rep.CopyNew().AsQueryable().ToListAsync();
		List<AggrementPluginManage> plugins = await _pluginRep.CopyNew().AsQueryable().ToListAsync();
		_cache.Set("BrandModels", all);
		_cache.Set("AggrementPlugins", plugins);
		foreach (AggrementPluginManage plugin in plugins)
		{
			try
			{
				if (plugin.Status == 1)
				{
					IAggrementPlugin pluginService = AggrementPluginUtil.GetPluginService(plugin.AssemblyName, plugin.Path);
					if (pluginService != null && !pluginService.IsRunning())
					{
						pluginService.Start(plugin.EParams);
					}
				}
			}
			catch
			{
			}
		}
	}
}
